package com.mwy.springbootquartzdemo2.config;

import com.mwy.springbootquartzdemo2.job.MyJob;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

//定时任务配置类
@Configuration
public class QuartzConfig {
    //1.创建job对象
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean(){
        JobDetailFactoryBean factory = new JobDetailFactoryBean();
        //关联job类
        factory.setJobClass(MyJob.class);
        return factory;
    }

    //2.创建Trigger对象(需要传入上一步的对象)
    //（1）简单的Trigger对象
    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
        SimpleTriggerFactoryBean factory = new SimpleTriggerFactoryBean();
        //关联jobDetail
        factory.setJobDetail(jobDetailFactoryBean.getObject());
        //表示多少毫秒循环执行一次
        factory.setRepeatInterval(3000);
        //设置重复次数
        factory.setRepeatCount(3);    //重复4次
        return factory;
    }


    //2.创建Trigger对象(需要传入上一步的对象)
    //（2）简单的Trigger对象
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean (JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
        //关联jobDetail
        factory.setJobDetail(jobDetailFactoryBean.getObject());
        //设置触发时间
        factory.setCronExpression("*/5 * * * * ?");
        return factory;
    }

    //3.创建schudler对象
    @Bean("scheduler")
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean,SimpleTriggerFactoryBean simpleTriggerFactoryBean){
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        //关联触发器（可以配置多个）
        factory.setTriggers(cronTriggerFactoryBean.getObject(),simpleTriggerFactoryBean.getObject());
        return factory;
    }

}
